package hng.util;

import hng.model.LoginUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;

import org.springframework.stereotype.Component;

@Slf4j
@Component
public class JWTUtil {

    private static final long EXPIRE = 1000 * 60 * 60 * 24;
    private static final String TOKEN_PREFIX = "HNG";
    private static final String SUBJECT = "huiong";

    /**
     * 这个HS256密钥从User的keyuitl生成
     */
    private static SecretKey getSecretKey() {
        byte[] decodedKey = Base64.getDecoder().decode("vR89T49ZrLAZ17v/Jdofup2x/aftHbb+eTmj5+4WJ6Q=");
        return new SecretKeySpec(decodedKey, 0, decodedKey.length, "HmacSHA256");
    }
    public static String getJsonWebToken(LoginUser loginUser) {
        if (loginUser == null) {
            throw new NullPointerException("对象为空");
        }

        String token = Jwts.builder().setSubject(SUBJECT)
                .claim("id", loginUser.getId())
                .claim("phone", loginUser.getPhone())
                .claim("role", loginUser.getRole())
                .claim("storeId", loginUser.getStoreId())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(getSecretKey())
                .compact();

        return TOKEN_PREFIX + token;
    }

    public static Claims checkJWT(String token) {
        try {
            final Claims claims = Jwts.parserBuilder()
                    .setSigningKey(getSecretKey())
                    .build()
                    .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                    .getBody();
            return claims;
        } catch (Exception e) {
            return null;
        }
    }
}
